#define _CRT_SECURE_NO_WARNINGS
#include"add.h"

void Print(int* a, int n) {
	for (int i = 0; i < n; i++) {
		printf("%d ", a[i]);
	}
	printf("\n");
}

void swap(int* a, int* b) {
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void BubbleSort1(int* a, int n) {
	for (int i = 0; i < n - 1; i++) {
		for (int j = i + 1; j < n; j++) {
			if (a[i] > a[j]) {
				swap(&a[i], &a[j]);
			}
		}
	}
}

void BubbleSort2(int* a, int n) {
	for (int i = 0; i < n - 1; i++) {
		int ret = 0;
		for (int j = 0; j < n - 1 - i; j++) {
			if (a[j] > a[j + 1]) {
				swap(&a[j], &a[j + 1]);
				ret = 1;
			}
		}
		if (ret == 0)break;
	}
}

void InsertSort(int* a, int n) {
	for (int i = 1; i < n; i++) {
		int tmp = a[i];
		int j = i - 1;
		while (j >= 0) {
			if (a[j] > tmp) a[j + 1] = a[j];
			else break;
			j--;
			a[j + 1] = tmp;
		}
	}
}


void ShellSort(int* a, int n) {
	int gap = n / 2;
	while (gap >= 1) {
		for (int i = gap; i < n; i++) {
			int tmp = a[i];
			int j = i - gap;
			while (j >= 0) {
				if (a[j] > tmp)a[j + gap] = a[j];
				else break;
				j -= gap;
			}
			a[j + gap] = tmp;
		}
		gap /= 2;
	}
}

void SelectSort(int* a, int n) {
	for (int i = 0; i < n - 1; i++) {
		int mini = i;
		for (int j = i + 1; j < n; j++) {
			if (a[j] < a[mini])mini = j;
		}
		swap(&a[i], &a[mini]);
	}
}

void SelectSort1(int* a, int n) {
	for (int left = 0, right = n - 1; left < right; left++, right--) {
		int maxi = left;
		int mini = left;
		for (int i = left; i <= right; i++) {
			if (a[i] > a[maxi])maxi = i;
			if (a[i] < a[mini])mini = i;
		}
		swap(&a[left], &a[mini]);
		if (left == maxi)swap(&a[mini], &a[right]);
		else swap(&a[maxi], &a[right]);
	}
}

void CountSort(int* a, int n) {
	int tmax = a[0];
	int tmin = a[0];
	for (int i = 1; i < n; i++) {
		if (a[i] > tmax)tmax = a[i];
		if (a[i] < tmin)tmin = a[i];
	}
	int* tmp = (int*)calloc(tmax-tmin+1,sizeof(int));
	for (int i=0; i < n; i++) {
		tmp[a[i] - tmin]++;
	}
	for (int i = 0,j=0; i < tmax-tmin+1; i++) {
		while (tmp[i] > 0) {
			a[j++] = i + tmin;
			tmp[i]--;
		}
	}
	free(tmp);
}


void QuickSort1(int* a, int begin ,int end) {
	if (begin <= end)return;
	int tmp = a[begin];
	int left = begin + 1;
	int right = end;
	while (left < right) {
		while (left < right && a[right] >= tmp)right--;
		while (left < right && a[left] <= tmp)left++;
		swap(&a[left], &a[right]);
	}
	swap(&a[left], &a[begin]);
	QuickSort1(a, begin, left - 1);
	QuickSort1(a,  left + 1,end);
}

void QuickSort2(int* a, int begin, int end) {

}